package sc.prototype.common;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;

public class FileUtil {

    static Logger logger = LoggerFactory.getLogger(FileUtil.class);

    public static String getCPFileAsStringMutely(String classpathFile) {
        return getCPFileAsStringMutely(classpathFile, "UTF-8");
    }

    public static String getCPFileAsStringMutely(String classpathPath, String encoding) {
        try {
            return getCPFileAsString(classpathPath, encoding);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取CLASSPATH下文件文本内容
     * @param classpathFile 相对CLASSPATH路径
     * @param encoding 文件编码方式
     * @return 文本内容
     * @throws IOException
     */
    public static String getCPFileAsString(String classpathFile, String encoding) throws IOException {
        InputStream in = null;
        try {
            in = new ClassPathResource(classpathFile).getInputStream();
            String ret = StreamUtil.readText(in, encoding);
            return ret;
        } catch (IOException e) {
            throw e;
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }

    public static String getFileAsString(String filePath, String encoding) throws IOException {
        InputStream in = null;
        try {
            in = new FileInputStream(filePath);
            String ret = StreamUtil.readText(in, encoding);
            return ret;
        } catch (IOException e) {
            throw e;
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }

    public static void main(String[] args) {
        //Get CLASSPATH relative path file OK~
        logger.info("Test getCPFileAsStringMutely(/sc/prototype/common/demo/test.xml)\r\n{}",
                FileUtil.getCPFileAsStringMutely("/sc/prototype/common/demo/test.xml", "UTF-8"));
        //Get CLASSPATH relative path2 file OK~
        logger.info("Test getCPFileAsStringMutely(sc/prototype/common/demo/test.xml)\r\n{}",
                FileUtil.getCPFileAsStringMutely("sc/prototype/common/demo/test.xml", "UTF8"));
        //Can not get ABSOLUTE path file!
        logger.info("Test getCPFileAsStringMutely(D:/Configs/ReadMe.txt)\r\n{}",
                FileUtil.getCPFileAsStringMutely("D:/Configs/ReadMe.txt", "UTF-8"));
    }
}
